package com.fms.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fms.common.vo.Result;
import com.fms.sys.entity.Site;
import com.fms.sys.service.ISiteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 站点信息控制器
 * </p>
 *
 * @author Jinfeng
 * @since 2024-03-23
 */
@RestController
@RequestMapping("/site")
public class SiteController {
    @Autowired
    private ISiteService siteService;

    @GetMapping("/list")
    public Result<Map<String, Object>> getSiteList(
            @RequestParam(value = "pageNo", defaultValue = "1") Long pageNo,
            @RequestParam(value = "pageSize", defaultValue = "10") Long pageSize,
            @RequestParam(value = "categoryId", required = false) Long categoryId,
            @RequestParam(value = "siteName", required = false) String siteName) {

        LambdaQueryWrapper<Site> wrapper = new LambdaQueryWrapper<>();
        if (categoryId != null) {
            wrapper.eq(Site::getCategoryId, categoryId);
        }
        if (siteName != null && !siteName.isEmpty()) {
            wrapper.like(Site::getSiteName, siteName);
        }
        wrapper.orderByAsc(Site::getSortOrder);

        Page<Site> page = new Page<>(pageNo, pageSize);
        siteService.page(page, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("rows", page.getRecords());

        return Result.success(data);
    }

    @GetMapping("/category/{categoryId}")
    public Result<List<Site>> getSitesByCategory(@PathVariable("categoryId") Long categoryId) {
        LambdaQueryWrapper<Site> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Site::getCategoryId, categoryId)
                .orderByAsc(Site::getSortOrder);
        return Result.success(siteService.list(wrapper));
    }

    @GetMapping("/recommend")
    public Result<List<Site>> getRecommendSites() {
        LambdaQueryWrapper<Site> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Site::getIsRecommend, true)
                .orderByAsc(Site::getSortOrder);
        return Result.success(siteService.list(wrapper));
    }

    @PostMapping
    public Result<?> addSite(@RequestBody Site site) {
        siteService.save(site);
        return Result.success("新增站点成功");
    }

    @PutMapping
    public Result<?> updateSite(@RequestBody Site site) {
        siteService.updateById(site);
        return Result.success("修改站点成功");
    }

    @DeleteMapping("/{id}")
    public Result<?> deleteSite(@PathVariable("id") Long id) {
        if (!siteService.removeById(id)) {
            return Result.fail("删除失败，站点不存在");
        }
        return Result.success("删除站点成功");
    }

    @PutMapping("/sort")
    public Result<?> updateSort(@RequestBody List<Site> sites) {
        for (Site site : sites) {
            Site update = new Site();
            update.setId(site.getId());
            update.setSortOrder(site.getSortOrder());
            siteService.updateById(update);
        }
        return Result.success("更新排序成功");
    }

    @PutMapping("/{id}/recommend/{status}")
    public Result<?> updateRecommendStatus(
            @PathVariable("id") Long id,
            @PathVariable("status") Boolean status) {
        Site site = new Site();
        site.setId(id);
        site.setIsRecommend(status);
        siteService.updateById(site);
        return Result.success(status ? "设为推荐成功" : "取消推荐成功");
    }

    @PostMapping("/import-bookmarks")
    public Result<?> importBookmarks(
            @RequestParam("file") MultipartFile file,
            @RequestParam("browserType") String browserType,
            @RequestParam("autoCategory") boolean autoCategory) {
        try {
            // 1. 解析文件内容
            List<Map<String, String>> bookmarks = siteService.parseBookmarks(file, browserType);

            // 2. 自动分类（如果启用）
            if (autoCategory) {
                siteService.categorizeBookmarks(bookmarks);
            }

            // 3. 保存到数据库
            siteService.saveBookmarks(bookmarks);

            return Result.success("导入成功");
        } catch (Exception e) {
            return Result.fail("导入失败：" + e.getMessage());
        }
    }
}